package com.zqh.apicategoryquery.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Description :
 * @Author :kono淇杭哒、
 * @Create 2022-01-21 22:20
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer{
    /**
     * 功能描述:
     * 添加自定义序列化及反序列化其，解决LocalDateTime类型字段解析的问题，这样就不用一个一个字段通过注解去来解决
     * @param
     * @return
     * @author kono曾淇杭哒！
     * @date 2022/2/21 22:02
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        JavaTimeModule module = new JavaTimeModule();
        // 序列化器
        module.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 反序列化器
        // 这里添加的是自定义的反序列化器
        module.addDeserializer(LocalDateTime.class,
                new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(module);

        // add converter at the very front
        // 如果converter里有一个相同类型的mapper，那么先设置的那个会生效
        converters.add(0, new MappingJackson2HttpMessageConverter(mapper));
    }


}
